package com.ai.util;

import cn.hutool.core.util.ObjectUtil;
import com.ai.entity.function.FunctionPO;
import com.ai.entity.made.AlgorithmPackageStatus;
import com.ai.model.dto.CoalAudioVo;
import com.ai.model.param.AlgorithmPackageParam;
import com.ai.service.made.FunctionService;
import com.ai.service.made.IAlgorithmPackageStatusService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * @Author jiaok
 * @Date 2024-08-12 11:14
 */
@Service
@Slf4j
public class FileUploaderUtil {


    @Value("${audioUploadPath.url}")
    private String url ;

    @Resource
    private IAlgorithmPackageStatusService iAlgorithmPackageStatusService;

    @Resource
    private FunctionService functionService;

    /**
     * 实际存储算法文件
     * @param multipartFile 算法文件
     * @param algorithmPackageParam 界面入参
     * @return dto
     */
    public String uploadAlgorithmFile(MultipartFile multipartFile, AlgorithmPackageParam algorithmPackageParam){

        /**
         * 1.获取文件名，版本号，功能id，判断是否存在，不存在才能上传
         * 2.将算法传入到对应目录中
         */

        //获取文件名
        String originalFilename = multipartFile.getOriginalFilename();


        if (originalFilename == null){
            throw new RuntimeException("当前文件名不存在，请检查文件后重新上传");
        }
        FunctionPO functionPO = functionService.getById(algorithmPackageParam.getAlgorithmId());

        AlgorithmPackageStatus status = iAlgorithmPackageStatusService.getOne(
                new QueryWrapper<AlgorithmPackageStatus>().eq("function_id", algorithmPackageParam.getAlgorithmId()).eq("version", algorithmPackageParam.getVersion()));
        if (status!=null){
            throw new RuntimeException("已存在当前版本的该算法，请重新选择版本进行上传");
        }

        //文件夹路径
        String dirPath = url + "/" + functionPO.getType() + "/" + algorithmPackageParam.getVersion();
        //文件
        String filePath = dirPath +"/" +originalFilename;

        //构建文件对象
        File dir = new File(dirPath);
        //创建需要存储音频的文件夹
        if (!dir.exists()) {
            boolean created = dir.getParentFile().mkdirs();
            if (!created) {
                log.error("创建父目录异常");
            }
            boolean mkdir = dir.mkdir();
            if (!mkdir) {
                log.error("创建文件夹异常");
            }
        }
        File file = new File(filePath);

        try( InputStream inputStream = multipartFile.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(file)
        ){
            byte[] bytes = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, bytesRead);
            }
            return filePath;
        }catch (IOException e){
            log.info("=========================== 算法文件上传异常,{}  ===========================",e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 上传音频文件
     * @param audioFile  音频文件
     * @param coalAudioVo 文件信息
     * @return
     */
    public HashMap<String, String> uploadAudio(MultipartFile audioFile, CoalAudioVo coalAudioVo) {

        //获取文件名
        String originalFilename = audioFile.getOriginalFilename();


        if (originalFilename == null){
            throw new RuntimeException("当前文件名不存在，请检查文件后重新上传");
        }
        FunctionPO functionPO = functionService.getById(coalAudioVo.getFunctionId());
        if (ObjectUtil.isEmpty(functionPO)){
            throw new RuntimeException("对应功能不存在");
        }

        //文件夹路径
        String dirPath = url + "/" + functionPO.getType() + "/" + "audioFile";
        //文件
        String filePath = dirPath +"/" +originalFilename;

        //构建文件对象
        File dir = new File(dirPath);
        //创建需要存储音频的文件夹
        if (!dir.exists()) {
            boolean created = dir.getParentFile().mkdirs();
            if (!created) {
                log.error("创建父目录异常");
            }
            boolean mkdir = dir.mkdir();
            if (!mkdir) {
                log.error("创建文件夹异常");
            }
        }
        File file = new File(filePath);

        try( InputStream inputStream = audioFile.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(file)
        ){
            byte[] bytes = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, bytesRead);
            }
            HashMap<String, String> hashMap = new HashMap<>(16);
            hashMap.put("filePath",filePath);
            hashMap.put("originalFilename",originalFilename);
            return hashMap;
        }catch (IOException e){
            log.info("=========================== 音频文件上传异常,{}  ===========================",e.getMessage());
            e.printStackTrace();
        }

        return null;
    }
}
